'use strict';
 
function exec (key, value, options) { 
    if (arguments.length > 1) {
        options = Object.assign({ path: '/' }, Cookies.basicSetup.options, options);

        // IE不支持"max-age"，所以使用expires
        if ('number' === typeof options.expires) {
            options.expires = new Date(new Date() * 1 + options.expires * 864e+5);
        } 
        options.expires = options.expires ? options.expires.toUTCString() : '';

        try {
            var result = JSON.stringify(value);
            if (/^[\{\[]/.test(result)) {
                value = result;
            }
        } catch (e) {}

        value = Cookies.basicSetup.encrypt ?
            Cookies.basicSetup.encrypt(value, key):
            encodeURIComponent(String(value)).
            replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);

        key = encodeURIComponent(String(key))
            .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
            .replace(/[\(\)]/g, escape);

        var stringified = '';
        for (var name in options) {
            if (!options[name]) {
                continue;
            }
            stringified += ';' + name;
            if (options[name] === true) {
                continue;
            }

            stringified += '=' + options[name].split('; ')[0];
        }

        return (document.cookie = key + '=' + value + stringified);
    }

    // 读取 
    var jar = {};
    var decode = function (s) {
        return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
    };
    var cookies = document.cookie ? document.cookie.split('; ') : []; 

    for (var i = 0; i < cookies.length; i++) {
        var parts = cookies[i].split('=');
        var cookie = parts.slice(1).join('=');

        if (!this.json && cookie.charAt(0) === '"') {
            cookie = cookie.slice(1, -1);
        }

        try {
            var name = decode(parts[0]);
            cookie = Cookies.basicSetup.decrypt ?
                Cookies.basicSetup.decrypt(cookie, name) :
                decode(cookie);

            if (this.json) {
                try {
                    cookie = JSON.parse(cookie);
                } catch (e) {}
            }

            jar[name] = cookie;

            if (key === name) {
                break;
            }
        } catch (e) {
            e.message = '[Cookie Error] ' + e.message;
            throw e;
        }
    }

    return key ? jar[key] : jar;
}

export class Cookies{
    // 存储
    set(key, value, options){
        return exec(key, value, options);
    }

    // 读取
    get(key){
        return exec.call(exec, key);
    }

    // 删除
    remove(key, options) {
        exec(key, '', Object.assign({}, options, { expires: -1 }));
    }

    // 转换为JSON
    toJSON(key) {
        return exec.call({ json: true  }, key);
    }

    // 全局配置
    configure( options ){
        if ('object' !== typeof options) {
            throw new Error('[Cookie Error] The API `configure` must have an object parameter !');
        } 
        if ('function' === typeof options.encrypt) {
            Cookies.basicSetup.encrypt = options.encrypt;
            delete options.encrypt;
        }
        if ('function' === typeof options.decrypt) {
            Cookies.basicSetup.decrypt = options.decrypt;
            delete options.decrypt;
        }
        Cookies.basicSetup.options = Object.assign({}, Cookies.basicSetup.options, options);
    }
};

// 全局用户配置
Cookies.basicSetup = {
    encrypt: null, // 加密
    decrypt: null, // 解密
    options: null  // 用户配置 
}; 
